/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.playground.core.service.impl;

import com.playground.core.entity.GameTitle;
import com.playground.core.entity.LoggedPlayer;
import com.playground.core.entity.Room;
import com.playground.core.entity.RoomStatus;
import com.playground.core.repository.RoomRepository;
import com.playground.core.service.RoomService;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import javax.inject.Inject;
import org.springframework.stereotype.Service;

/**
 *
 * @author Tiago Peres
 */
@Service("roomService")
public class RoomServiceImpl implements RoomService {
    
    @Inject
    private RoomRepository roomRepository;

    public Iterator<Room> getFullRoomsIterator() {
        return roomRepository.findRoomByStatus(RoomStatus.full).iterator();
    }

    public Iterator<Room> getReadyRoomsIterator() {
        return roomRepository.findRoomByStatus(RoomStatus.ready).iterator();
    }

    public Iterator<Room> getRefusedRoomsIterator() {
        return roomRepository.findRoomByStatus(RoomStatus.refused).iterator();
    }

    public boolean closeRoom(Room room) {
        if (null != roomRepository.findOne(room.getId())){
            room.setGame(null);
            room.setGameTitle(null);
            room.setPlayers(null);
            room.setWaitingForPlayersConfirmationSince(null);
            room.setStatus(RoomStatus.closed);
            roomRepository.save(room);
            return true;
        }
        return false;
    }

    public Room setUpNewRoom(GameTitle gameTitle) {
        if (!RoomStatusUpdater.getInstance().isRunning()){
            RoomStatusUpdater.getInstance().setRoomRepository(roomRepository);
            RoomStatusUpdater.getInstance().start();
        }
        List<Room> closed = roomRepository.findRoomByStatus(RoomStatus.closed);
        Room r;
        if (closed.size() > 0){
            r = closed.get(0);
        } else{
            r = new Room();
        }
        r.setGameTitle(gameTitle);
        r.setMaxPlayers(gameTitle.getMaximumNumberOfPlayers());
        r.setPlayers(new ArrayList<LoggedPlayer>());
        r.setStatus(RoomStatus.opened);
        r = roomRepository.save(r);
        return r;
    }
    
}
